let fs = require('fs').promises;
let path = require('path');
let { PDFDocument } = require('pdf-lib');
let sharp = require('sharp');

async function sortFilesByBirthtime(imageDir, imageFiles) {
  // 获取所有文件的状态信息
  let fileStats = await Promise.all(
    imageFiles.map(file => fs.stat(path.join(imageDir, file))),
  );
  // 将文件名和对应的 birthtime 组合成键值对
  let filesWithBirthtime = imageFiles.map((file, index) => {
    let birthtime = '';
    if (file.includes('UC多图下载')) {
      birthtime = Number(file.match(/\d+/g).join(''));
    } else {
      // birthtime = fileStats[index].birthtime.getTime();
      birthtime = Number(file.match(/\d+/g).join('').substring(0, 'YYYYMMDDHHmm'.length));
    }
    return { filename: file, birthtime };
  });
  // 按照 birthtime 排序
  filesWithBirthtime.sort((a, b) => a.birthtime - b.birthtime);
  // 提取排序后的文件名
  return filesWithBirthtime.map(item => item.filename);
}

async function imagesToPdf(imageDir, outputPdfPath) {
  try {
    // 获取目录中的所有文件名
    let files = await fs.readdir(imageDir);
    // 过滤出只包含图片文件的数组
    let imageFiles = files.filter(file => /\.(webp|png|jpg|jpeg)$/i.test(file));
    if (imageFiles.length === 0) {
      console.log('No image files found.');
      return;
    }
    imageFiles = await sortFilesByBirthtime(imageDir, imageFiles);
    let pdfDoc = await PDFDocument.create();
    // 遍历每张图片并添加到 PDF 中
    let currIndex = 1;
    for (let file of imageFiles) {
      let imagePath = path.join(imageDir, file);
      let imageBuffer = await fs.readFile(imagePath);
      let jpgImageBytes = await sharp(imageBuffer).toFormat('jpeg').toBuffer();
      let image = await pdfDoc.embedJpg(jpgImageBytes);
      let dimensions = image.scale(1.0); // 不缩放图片
      let targetWidth = 612; // A4 页面宽度为 612 点 (72 DPI)
      // 计算宽高比并据此调整高度
      let aspectRatio = dimensions.width / dimensions.height;
      let targetHeight = targetWidth / aspectRatio;
      let page = pdfDoc.addPage([targetWidth, targetHeight]);
      page.drawImage(image, {
        x: 0,
        y: 0,
        width: targetWidth,
        height: targetHeight,
      });
      console.log(`Added ${file} to PDF. ${currIndex}`);
      currIndex++;
    }
    // 将生成的 PDF 写入文件
    let pdfBytes = await pdfDoc.save();
    await fs.writeFile(outputPdfPath, pdfBytes);
    console.log(`PDF saved as ${outputPdfPath}`);
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

function main() {
  let index = 1;
  if (index === 1) {
    let imageDirectory = 'D:\\360安全浏览器下载\\新建文件夹';
    // let outputPath = `./pdf/00000018.pdf`;
    let outputPath = `D:\\360安全浏览器下载\\3390-4091.pdf`;
    imagesToPdf(imageDirectory, outputPath);
  }
  else if (index === 2) {
    async function batchDir(baseDir) {
      // 读取指定目录的内容
      let items = await fs.readdir(baseDir, { withFileTypes: true });
      for (let item of items) {
        if (item.isDirectory()) {
          let oldPath = path.join(baseDir, item.name);
          let newPath = path.join(baseDir, item.name + '.pdf');
          await imagesToPdf(oldPath, newPath);
        }
      }
    }

    batchDir(
      `D:\\360安全浏览器下载`,
      `D:\\360安全浏览器下载`,
    );
  }
  else if (index === 3) {
    let imageDirectory = './har/images';
    let outputPath = `./har/images/xxx.pdf`;
    imagesToPdf(imageDirectory, outputPath);
  }
}

main();
